package cn.edu.lnpu.manage.cms.service;

import cn.edu.lnpu.common.exception.ExceptionCast;
import cn.edu.lnpu.common.model.response.CommonCode;
import cn.edu.lnpu.common.model.response.QueryResponseResult;
import cn.edu.lnpu.common.model.response.QueryResult;
import cn.edu.lnpu.common.model.response.ResponseResult;
import cn.edu.lnpu.domain.cms.CmsTemplate;
import cn.edu.lnpu.domain.cms.CmsTemplateContent;
import cn.edu.lnpu.domain.cms.response.CmsCode;
import cn.edu.lnpu.manage.cms.dao.CmsTemplateRepository;
import cn.hutool.core.io.IoUtil;
import com.mongodb.client.gridfs.GridFSBucket;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class CmsTemplateService {

    @Autowired
    private CmsTemplateRepository cmsTemplateRepository;
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    public QueryResponseResult<CmsTemplate> list() {
        List<CmsTemplate> all = cmsTemplateRepository.findAll();
        if (all == null) {
            all = new ArrayList<>();
        }
        return new QueryResponseResult<>(CommonCode.SUCCESS, new QueryResult<>(all, all.size()));
    }

    public ResponseResult save(CmsTemplate cmsTemplate) {
        //如果模板名称和站点ID相同，更新数据
        if (StringUtils.isBlank(cmsTemplate.getTemplateId())) {
            cmsTemplate.setTemplateId(null);
        }
        cmsTemplateRepository.save(cmsTemplate);
        return ResponseResult.SUCCESS();
    }

    public ResponseResult saveTemplateContent(CmsTemplateContent content) {
        if (content == null) {
            ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
        }

        CmsTemplate cmsTemplate = cmsTemplateRepository.findById(content.getTemplateId()).orElse(null);
        if (cmsTemplate == null) {
            ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
        }
        String fileName = content.getName();
        FileInputStream inputStream = IoUtil.toStream(new File("d:\\" + fileName));
        //ByteArrayInputStream inputStream = IoUtil.toStream(content.getContent(), StandardCharsets.UTF_8);
        //定义输入流
        //向GridFS存储文件
        ObjectId objectId = gridFsTemplate.store(inputStream, content.getContent(), StandardCharsets.UTF_8);
        //得到文件ID
        String fileId = objectId.toString();
        cmsTemplate.setTemplateFileId(fileId);
        cmsTemplateRepository.save(cmsTemplate);
        return ResponseResult.SUCCESS();
    }
}
